package com.project.server;

import com.project.service.*;
import com.project.uitl.ServletFactory;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class SocketThread implements Runnable {
    private Socket socket;


    private static String header = "HTTP/1.1 200 OK\r\n" +
            "Content-Type: text/html;charSet=utf-8\r\n" +
            "\r\n";

    public SocketThread(Socket socket) {
        this.socket = socket;
//        启动线程
        new Thread(this).start();
    }


    @Override
    public void run() {

        try {
            //从socket 得到读取流 用于接收客户端发送的数据
            InputStream in = socket.getInputStream();
            //从socket 得到写入流  用于给客户端发送数据
            OutputStream out = socket.getOutputStream();
            //将输入流 封装成 Response 对象
            Response resp = new Response(out);

            //将输入流封装成 Request 对象
            Request req = new Request(in);
            System.out.println(req);
            //得到客户端输出数据
            String url = req.getUrl();
            //向客户端输出数据
            out.write(header.getBytes());
            Servlet service = ServletFactory.getService(url);
            if (service != null) {
                service.service(req, resp);
            } else {
                resp.sendFile(url);
            }

//            if ("land".equals(url)) {//登陆请求
//                LoginService login = new LoginService();
//                login.service(req, resp);
//            } else if ("findAll".equals(url)) {
//                FindAllService finAll = new FindAllService();
//                finAll.service(req, resp);
//            } else if ("add".equals(url)) {
//                AddService add = new AddService();
//                add.service(req, resp);
//            } else if ("del".equals(url)) {
//                DelService del = new DelService();
//                del.delService(req, resp);
//            } else if ("findById".equals(url)) {
//                FindByIdService findById = new FindByIdService();
//                findById.service(req, resp);
//            } else if ("update".equals(url)) {
//                UpdateService updateService = new UpdateService();
//                updateService.service(req, resp);
//            } else {
//                resp.sendFile(url);
//            }

            out.flush();

            //关闭流
            out.close();
            in.close();
            socket.close();

        } catch (Exception e) {

        }

    }
}
